package sipus.action.master;

import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.util.GenericAutowireComposer;
import org.zkoss.zul.A;
import org.zkoss.zul.Caption;
import org.zkoss.zul.Column;
import org.zkoss.zul.Columns;
import org.zkoss.zul.Detail;
import org.zkoss.zul.Grid;
import org.zkoss.zul.Groupbox;
import org.zkoss.zul.Label;
import org.zkoss.zul.ListModel;
import org.zkoss.zul.Row;
import org.zkoss.zul.RowRenderer;
import org.zkoss.zul.SimpleListModel;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Timer;

import sipus.common.Common;
import sipus.common.CommonPrivilages;
import sipus.database.hibernate.HibernateUtil;
import sipus.database.model.DetailLogLogin;
import sipus.database.model.LogLogin;
import sipus.database.model.LogUserActifity;
import sipus.database.model.Tbmuser;

public class LogLoginAction extends GenericAutowireComposer {

	/**
	 * 
	 */
	private static final long serialVersionUID = -5779730267402400328L;
	private Grid grid;

	private Textbox searchnama;

	@Override
	public void doAfterCompose(Component comp) throws Exception {
		// TODO Auto-generated method stub
		super.doAfterCompose(comp);
		if (session.getAttribute("usersTemp") == null
				|| !CommonPrivilages.checkPrevilages(CommonPrivilages.READ)) {
			session.removeAttribute("usersTemp");
			execution.sendRedirect("/logoff");
			return;
		}

		onSearchDefault(null);
	}

	private class TampilDetailLog implements EventListener {

		private LogLogin logLogin;
		private Detail detail;
		private Grid detailLogGrid;

		class DetailLogLoginRenderer implements RowRenderer {

			@Override
			public void render(final Row arg0, Object arg1) throws Exception {
				// TODO Auto-generated method stub
				final DetailLogLogin logLogin = (DetailLogLogin) arg1;

				final Detail detail = new Detail();
				detail.setParent(arg0);
				detail.addEventListener("onOpen",
						new TampilDetailUserAccessLog(detail, logLogin));

				new Label(logLogin.getKeterangan()).setParent(arg0);

				new Label(logLogin.getWaktu() == null ? ""
						: Common.dateFormat3.format(logLogin.getWaktu()))
						.setParent(arg0);

			}
		}

		private void createList() {
			Common.clear(detail);
			Groupbox groupbox = new Groupbox();
			groupbox.setParent(detail);
			groupbox.appendChild(new Caption("Daftar Rincian Kunjungan"));

			detailLogGrid = new Grid();
			detailLogGrid.setMold("paging");
			detailLogGrid.setPageSize(15);
			detailLogGrid.setParent(groupbox);
			detailLogGrid.setWidth("100%");
			detailLogGrid.setHeight("100%");

			Columns columns = new Columns();
			columns.setMenupopup("auto");
			columns.setParent(detailLogGrid);

			Column column = new Column();
			column.setParent(columns);
			column.setLabel("");
			column.setWidth("35px");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Menu yang diakses");
			column.setWidth("75%");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Waktu");
			column.setAlign("center");
			column.setWidth("25%");

			loadDetailLogLogin();
		}

		@SuppressWarnings("unchecked")
		private void loadDetailLogLogin() {
			Session session = HibernateUtil.currentSession();
			List<DetailLogLogin> logLogins = session
					.createCriteria(DetailLogLogin.class)
					.add(Restrictions.eq("logLogin", logLogin))
					.addOrder(Order.desc("id")).list();

			ListModel strset = new SimpleListModel(logLogins);
			detailLogGrid.setRowRenderer(new DetailLogLoginRenderer());
			detailLogGrid.setModel(strset);
			detailLogGrid.renderAll();
			detailLogGrid.setOddRowSclass("non-odd");

		}

		public TampilDetailLog(Detail detail, LogLogin logLogin) {
			this.logLogin = logLogin;
			this.detail = detail;
		}

		@Override
		public void onEvent(Event arg0) throws Exception {
			Common.clear(detail);
			if (detail.isOpen()) {
				createList();
			}
		}

	}

	private class TampilDetailUserAccessLog implements EventListener {

		private DetailLogLogin detailLogLogin;
		private Detail detail;
		private Grid logUserActifityGrid;

		class DetailLogLoginRenderer implements RowRenderer {

			@Override
			public void render(final Row arg0, Object arg1) throws Exception {
				// TODO Auto-generated method stub
				final LogUserActifity logUserActifity = (LogUserActifity) arg1;

				new Label(logUserActifity.getKeterangan()).setParent(arg0);
				new Label(logUserActifity.getKeterangan12() == null ? ""
						: logUserActifity.getKeterangan12()).setParent(arg0);
				new Label(logUserActifity.getKeterangan1()).setParent(arg0);

				new Label(logUserActifity.getImg()).setParent(arg0);
				new Label(logUserActifity.getEvent()).setParent(arg0);

				new Label(logUserActifity.getWaktu() == null ? ""
						: Common.dateFormat3.format(logUserActifity.getWaktu()))
						.setParent(arg0);

			}
		}

		private void createList() {
			Common.clear(detail);
			Groupbox groupbox = new Groupbox();
			groupbox.setParent(detail);
			groupbox.appendChild(new Caption("Daftar Rincian Akses"));

			logUserActifityGrid = new Grid();
			logUserActifityGrid.setMold("paging");
			logUserActifityGrid.setPageSize(15);
			logUserActifityGrid.setParent(groupbox);
			logUserActifityGrid.setWidth("100%");
			logUserActifityGrid.setHeight("100%");

			Columns columns = new Columns();
			columns.setMenupopup("auto");
			columns.setParent(logUserActifityGrid);

			Column column = new Column();
			column.setParent(columns);
			column.setLabel("Keterangan 1");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Keterangan 2");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Keterangan 3");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Image");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Event");

			column = new Column();
			column.setParent(columns);
			column.setLabel("Waktu");
			column.setAlign("center");

			loadDetailLogLogin();
		}

		@SuppressWarnings("unchecked")
		private void loadDetailLogLogin() {
			Session session = HibernateUtil.currentSession();
			List<LogUserActifity> logUserActifity = session
					.createCriteria(LogUserActifity.class)
					.add(Restrictions.eq("detailLogLogin", detailLogLogin))
					.addOrder(Order.desc("id")).list();

			ListModel strset = new SimpleListModel(logUserActifity);
			logUserActifityGrid.setRowRenderer(new DetailLogLoginRenderer());
			logUserActifityGrid.setModel(strset);
			logUserActifityGrid.renderAll();
			logUserActifityGrid.setOddRowSclass("non-odd");

		}

		public TampilDetailUserAccessLog(Detail detail, DetailLogLogin logLogin) {
			this.detailLogLogin = logLogin;
			this.detail = detail;
		}

		@Override
		public void onEvent(Event arg0) throws Exception {
			Common.clear(detail);
			if (detail.isOpen()) {
				createList();
			}
		}

	}

	class LogLoginRenderer implements RowRenderer {

		@Override
		public void render(final Row arg0, Object arg1) throws Exception {
			// TODO Auto-generated method stub
			final LogLogin logLogin = (LogLogin) arg1;
			if ((logLogin.getSuccess_status() != null && !logLogin
					.getSuccess_status())) {
				arg0.setStyle("background-color: red;font-weight: bold;");
			}

			final Detail detail = new Detail();
			detail.setParent(arg0);
			detail.addEventListener("onOpen", new TampilDetailLog(detail,
					logLogin));

			final Label time = new Label("");

			Long diff = null;
			Long diffDetik = 0L;
			Long diffMenit = 0L;
			Long diffJam = 0L;
			Timer timer = null;
			if (logLogin.getSuccess_status() != null
					&& !logLogin.getSuccess_status()) {
				time.setValue("");
			} else if (logLogin.getLogin() != null
					&& logLogin.getLogout() != null) {
				diff = logLogin.getLogout().getTime()
						- logLogin.getLogin().getTime();
				diffDetik = (diff / (1000/* * 60 * 60 * 24 */)) % 60;
				diffMenit = (diff / (1000 * 60 /** 60 * 24 */
				)) % 60;
				diffJam = (diff / (1000 * 60 * 60 /** 24 */
				));
				time.setValue(diff == null ? "" : Common.numberFormat
						.format(diffJam)
						+ " jam "
						+ Common.numberFormat.format(diffMenit)
						+ " menit "
						+ Common.numberFormat.format(diffDetik) + " detik");
			} else if (logLogin.getLogin() != null) {
				timer = new Timer(1000);

				timer.setRepeats(true);

				timer.addEventListener("onTimer", new EventListener() {

					@Override
					public void onEvent(Event arg0) throws Exception {

						Long diff = null;
						Long diffDetik = 0L;
						Long diffMenit = 0L;
						Long diffJam = 0L;
						diff = new Date().getTime()
								- logLogin.getLogin().getTime();
						diffDetik = (diff / (1000/* * 60 * 60 * 24 */)) % 60;
						diffMenit = (diff / (1000 * 60 /** 60 * 24 */
						)) % 60;
						diffJam = (diff / (1000 * 60 * 60 /** 24 */
						));

						time.setValue(diff == null ? "" : Common.numberFormat
								.format(diffJam)
								+ " jam "
								+ Common.numberFormat.format(diffMenit)
								+ " menit "
								+ Common.numberFormat.format(diffDetik)
								+ " detik");

					}
				});
			}

			new Label(logLogin.getLogin() == null ? ""
					: Common.dateFormat3.format(logLogin.getLogin()))
					.setParent(arg0);
			new Label(logLogin.getLogout() == null ? "Belum/tidak logout"
					: Common.dateFormat3.format(logLogin.getLogout()))
					.setParent(arg0);
			time.setParent(arg0);
			A myIp = new A(logLogin.getIp());
			myIp.setTarget("new");
			myIp.setHref("http://whatismyipaddress.com/ip/" + logLogin.getIp());
			myIp.setParent(arg0);

			Tbmuser tbmuser = logLogin.getTbmuser();

			String nama = tbmuser == null ? "" : tbmuser.getUserNama();
			new Label(nama).setParent(arg0);
			new Label(tbmuser == null || tbmuser.getUserRole() == null ? ""
					: tbmuser.getUserRole().getRoleName()).setParent(arg0);

			new Label(logLogin.getSuccess_status() == null
					|| logLogin.getSuccess_status() ? "Sukses" : "Gagal")
					.setParent(arg0);
			new Label(logLogin.getDescription() == null ? ""
					: logLogin.getDescription()).setParent(arg0);

			if (timer != null) {
				timer.setParent(arg0);
			}

		}
	}

	@SuppressWarnings("unchecked")
	public void onSearchDefault(Event event) {
		Session session = HibernateUtil.currentSession();
		List<LogLogin> logLogin = session
				.createCriteria(LogLogin.class)
				.createAlias("tbmuser", "tbmuser", Criteria.LEFT_JOIN)
				.addOrder(Order.desc("id"))
				.add(Restrictions.ilike("tbmuser.userNama",
						searchnama.getValue(), MatchMode.ANYWHERE))
				.setMaxResults(Common.MAX_RESULT).list();
		ListModel strset = new SimpleListModel(logLogin);
		grid.setRowRenderer(new LogLoginRenderer());
		grid.setModel(strset);

		grid.renderAll();
		// grid.setOddRowSclass("non-odd");

	}

}
